package com.qudian.pay.redis;

import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import com.google.common.primitives.Primitives;
import com.qudian.pay.core.utils.JdkSerializer;
import com.qudian.pay.redis.exception.RedisException;
import com.qudian.pay.redis.support.IRedisSet;
import redis.clients.jedis.ShardedJedis;

/**
 * @Description: 简单的redis set操作管理器<br>
 */
@Component
public class RedisSetManager extends RedisManager implements IRedisSet<String> {
	
	@Override
	public void add(String key, Object value) {
		ShardedJedis jedis = this.getPool().getResource();
		try {
			jedis.sadd((key == null ? null : key.getBytes(charset)),
					null == value ? JdkSerializer.serialize(StringUtils.EMPTY) : JdkSerializer.serialize(value));
		} catch (Exception e) {
			throw new RedisException(-1, e.getMessage(), e);
		} finally {
			jedis.close();
		}
	}
	
	@Override
	public boolean isMemberOf(String key, Object value) {
		ShardedJedis jedis = this.getReadPool().getResource();
		try {
			return jedis.sismember((key.getBytes(charset)), JdkSerializer.serialize(value));
		} catch (Exception e) {
			throw new RedisException(-1, e.getMessage(), e);
		} finally {
			jedis.close();
		}
	}
	
	@Override
	public Set<Object> members(String key) {
		Set<Object> sets = null;
		ShardedJedis jedis = this.getReadPool().getResource();
		try {
			Set<byte[]> tmpSet = jedis.smembers(key.getBytes(charset));
			if (null != tmpSet && !tmpSet.isEmpty()) {
				sets = new HashSet<Object>(tmpSet.size());
				for (byte[] s : tmpSet) {
					sets.add(JdkSerializer.deSerialize(s));
				}
			}
		} catch (Exception e) {
			throw new RedisException(-1, e.getMessage(), e);
		} finally {
			jedis.close();
		}
		return sets;
	}
	
	@Override
	public <T> T pop(String key, Class<T> classOfT) {
		ShardedJedis jedis = this.getReadPool().getResource();
		try {
			byte[] bytes = jedis.get((key == null ? null : ((String) key).getBytes(charset)));
			if (null == bytes)
				return null;
			return Primitives.wrap(classOfT).cast(JdkSerializer.deSerialize(bytes));
		} catch (Exception e) {
			throw new RedisException(-1, e.getMessage(), e);
		} finally {
			jedis.close();
		}
	}
}
